package wetalk.software.bupt.com.wetalk.view.activity;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jyt.message.Message;
import com.jyt.util.MySerializable;

import org.json.JSONException;
import org.json.JSONObject;

import wetalk.software.bupt.com.wetalk.DB.WeTalkDB;
import wetalk.software.bupt.com.wetalk.GloableParams;
import wetalk.software.bupt.com.wetalk.R;
import wetalk.software.bupt.com.wetalk.application.MyApplication;
import wetalk.software.bupt.com.wetalk.application.UserManager;
import wetalk.software.bupt.com.wetalk.communicate.AndroidClientService;
import wetalk.software.bupt.com.wetalk.model.po.ChatUser;
import wetalk.software.bupt.com.wetalk.model.po.User;
import wetalk.software.bupt.com.wetalk.util.WeTalkConfig;
import wetalk.software.bupt.com.wetalk.util.WeTalkNetUtil;
import wetalk.software.bupt.com.wetalk.view.dialog.CustomDialog;

public class UserInfoActivity extends AppCompatActivity {
    private static final String TAG="XIAOMA?UserInfoActivity";

    private ImageView infoImage;
    private TextView infoName;
    private TextView infoDepartment;
    private TextView infoPhoneNumber;
    private TextView infoEmail;
    private AndroidClientService.SendBinder sendBinder;
    private DelFriReceiver receiver;

    private ServiceConnection connection=new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            sendBinder= (AndroidClientService.SendBinder) iBinder;
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
        }
    };


    public static void actionStart(Context context,User user,String action){
        Intent intent=new Intent(context,UserInfoActivity.class);
        intent.putExtra("user",user);
        intent.putExtra("action",action);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_info);
        initTitle();
        initBroadCast();

        Intent bindIntent = new Intent(this, AndroidClientService.class);
        this.bindService(bindIntent, connection, BIND_AUTO_CREATE);


        final User user=(User)getIntent().getSerializableExtra("user");
        String action=getIntent().getStringExtra("action");
        initViews(user);

        if(action.equals("look")){//如果action为look,则进入好友信息界面
            Button btSend=(Button)findViewById(R.id.bt_send);
            Button btDel=(Button)findViewById(R.id.bt_delete);
            btSend.setOnClickListener(new View.OnClickListener(){
                @Override
                public void onClick(View v) {
                    Intent intent=new Intent(UserInfoActivity.this,ChatActivity.class);
                    ChatUser chatUser=new ChatUser(user.getUserID(),user.getUserName(),user.getPassword(),
                            user.getAvatar(),user.getDepartment(),user.getPhone(),user.getEmail());
                    intent.putExtra("user",chatUser);
                    startActivity(intent);
                }
            });

            btDel.setOnClickListener(new View.OnClickListener(){
                @Override
                public void onClick(View v) {
                    AlertDialog.Builder dialog=new AlertDialog.Builder(UserInfoActivity.this);
                    dialog.setTitle("删除好友");
                    dialog.setMessage("是否删除该好友？");
                    dialog.setCancelable(false);
                    dialog.setPositiveButton("是", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if(WeTalkNetUtil.isNetworkAvailable(UserInfoActivity.this)){
                                sendDelFri(user.getUserID());
                                if(!UserInfoActivity.this.isFinishing()){
                                    CustomDialog.getDialog(UserInfoActivity.this,"正在删除...").show();
                                }
                            }else{
                                Toast.makeText(UserInfoActivity.this, "当前没有网络连接", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                    dialog.setNegativeButton("否", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                        }
                    });
                    dialog.show();
                }
            });

        } else if(action.equals("add")){//如果action为add,则进入未添加的用户信息界面
            Log.d(TAG,"添加好友信息");
            Button bt1=(Button)findViewById(R.id.bt_send);
            Button bt2=(Button)findViewById(R.id.bt_delete);
            bt1.setText("添加到通讯录");
            bt2.setVisibility(View.GONE);
            bt1.setOnClickListener(new View.OnClickListener(){
                @Override
                public void onClick(View v) {//点击按钮添加好友
                    Intent intent=new Intent(UserInfoActivity.this,VerifyActivity.class);
                    intent.putExtra("user",user);
                    startActivity(intent);
                }
            });
        }
    }

    private void initTitle(){
        RelativeLayout searchImgRight = (RelativeLayout) findViewById((R.id.rv_searchImg_right));
        searchImgRight.setVisibility(View.INVISIBLE);
        RelativeLayout rvRightImg=(RelativeLayout)findViewById(R.id.rv_img_right);
        rvRightImg.setVisibility(View.GONE);
        TextView txt=(TextView)findViewById(R.id.txt_title);
        txt.setText("详细资料");
        RelativeLayout rvLeftImg=(RelativeLayout)findViewById(R.id.rv_img_back);
        rvLeftImg.setVisibility(View.VISIBLE);
        rvLeftImg.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void initViews(User user){

        infoImage=(ImageView)findViewById(R.id.info_img);
        infoName=(TextView)findViewById(R.id.info_name);
        infoDepartment=(TextView)findViewById(R.id.info_department);
        infoPhoneNumber=(TextView)findViewById(R.id.info_phone_number);
        infoEmail=(TextView)findViewById(R.id.info_email);

        infoImage.setImageResource(R.drawable.a5);
        infoName.setText(user.getUserName());
        infoDepartment.setText(user.getDepartment());
        infoPhoneNumber.setText(user.getPhone());
        infoEmail.setText(user.getEmail());
    }

    private void sendDelFri(String id){
        final String userId= UserManager.getInstance(UserInfoActivity.this).getCurrentUser().getUserID();
        final String targetId = "sys_friend";
        final JSONObject json=new JSONObject();
        try {
            json.put("id",id);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Thread thread=new Thread(new Runnable() {
            @Override
            public void run() {

                byte[] bs;
                bs = MySerializable.object_bytes(json.toString());

                Message msg = new Message(userId,targetId,"delFri",bs);

                sendBinder.sendMessage(msg);
            }
        });
        thread.start();
        Log.d(TAG,"发送删除好友的请求"+json.toString());
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        this.unbindService(connection);
        unregisterReceiver(receiver);
    }

    //注册广播接收器
    private void initBroadCast(){
        //接收广播
        IntentFilter intentFilter=new IntentFilter("delFriRes");
         receiver=new DelFriReceiver();
        registerReceiver(receiver,intentFilter);
    }

    public class DelFriReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            SharedPreferences.Editor editor= MyApplication.getContext().getSharedPreferences("data",Context.MODE_PRIVATE).edit();
            CustomDialog.getDialog(MyApplication.getContext(),"正在删除...").close();
            UserInfoActivity.this.finish();
            Toast.makeText(context, "删除成功", Toast.LENGTH_SHORT).show();
            String content=intent.getStringExtra("content");
            String type=intent.getStringExtra("type");
            try {
                JSONObject json=new JSONObject(content);
                if(type.equals("delFriRes")){
                    WeTalkDB.create(MyApplication.getContext()).delFri(json.getString("id"));
                    editor.putString("isDel","yes");
                    editor.apply();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            Log.d(TAG,"DelFriReceiver-->"+content);
            abortBroadcast();
        }
    }

}
